const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const userModel = require("../model/user.model");
const { resObj } = require("../utils");
const { JWT_SECRET } = require("../config/config.base");

// 注册前验证
exports.registerRepeat = async (ctx, next) => {
  try {
    const { username, password } = ctx.request.body;
    console.log(username, "username");
    if (!username.trim() || !password.trim()) {
      ctx.body = resObj.error("账号和密码不能为空");
      return;
    }
    const user = await userModel.findOne({ where: { username } });
    console.log(user, "user");
    if (user) {
      ctx.body = resObj.error("账号已存在");
      return;
    }
    await next();
  } catch (error) {
    resObj.error(`参数错误: ${error}`);
  }
};
// 加密密码
exports.bcryptPass = async (ctx, next) => {
  const { password } = ctx.request.body;
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(password, salt);
  ctx.request.body.password = hash;
  console.log(salt, hash, "hash");
  await next();
};
// 登录前验证
exports.verifyLogin = async (ctx, next) => {
  try {
    const { username, password } = ctx.request.body;
    console.log(username, "username");
    if (!username.trim() || !password.trim()) {
      ctx.body = resObj.error("账号和密码不能为空");
      return;
    }
    const userMd = await userModel.findOne({ where: { username } });
    if (!userMd) {
      ctx.body = resObj.error("账号或密码错误");
      return;
    }
    const user = userMd.dataValues;
    console.log(user, "user");

    const pass = bcrypt.compareSync(password, user.password);
    if (!pass) {
      ctx.body = resObj.error("账号或密码错误");
      return;
    }
    ctx.user = user;
    await next();
  } catch (error) {
    resObj.error(`参数错误: ${error}`);
  }
};
// 验证权限
exports.verifyToken = async (ctx, next) => {
  const { authorization = "" } = ctx.request.headers;
  const token = authorization.replace("Bearer ", "");
  try {
    const user = jwt.verify(token, JWT_SECRET);
    ctx.user = user;
    await next();
  } catch (error) {
    ctx.body = resObj.error("身份失效");
  }
};
